package com.gitee.feizns.explore.data_structure.linked_list.singly.detectCycle;

import com.gitee.feizns.explore.data_structure.linked_list.singly.ListNode;

import java.util.HashSet;
import java.util.Set;

/**
 * @author feizns
 * @since 2020/3/6
 */
public class DetectCycle {

    public static ListNode detectCycle(ListNode head) {
        Set<ListNode> before = new HashSet<>();
        ListNode tmp = head;
        while ( tmp != null ) {
            if ( before.contains(tmp) )
                return tmp;
            before.add(tmp);
            tmp = tmp.next;
        }
        return null;
    }

    private static ListNode detectCycle2(ListNode head) {
        ListNode fast = head, slow = head;
        if(fast == null || fast.next == null){
            return null;
        }
        fast = fast.next.next;
        slow = slow.next;
        while(fast != slow){
            if(fast == null || fast.next == null){
                return null;
            }
            fast = fast.next.next;
            slow = slow.next;
        }
        while(head != slow){
            head = head.next;
            slow = slow.next;
        }
        return head;
    }

}
